#!/usr/bin/env python3
import sys
import argparse
import json
import platform
from pathlib import Path
from typing import List, Dict, Optional

import pyphen
from tts_engines.engine_manager import TTSEngineManager


def split_into_syllables(word: str) -> List[str]:
    """将英文单词按音节拆分，返回音节列表。"""
    dic = pyphen.Pyphen(lang="en")
    hyphenated = dic.inserted(word)
    # pyphen 使用 '-' 插入音节边界
    syllables = [seg for seg in hyphenated.split("-") if seg]
    return syllables if syllables else [word]


def print_progress(current: int, total: int, prefix: str = "处理中") -> None:
    """显示进度条。"""
    bar_length = 30
    progress = float(current) / float(total)
    filled_length = int(bar_length * progress)
    bar = '█' * filled_length + '-' * (bar_length - filled_length)
    sys.stdout.write(f'\r{prefix}: [{bar}] {current}/{total} ({progress:.1%})')
    sys.stdout.flush()


def synthesize_tts(text: str, output_path: Path, tts_engine: str = "auto",
                  tts_source: str = "auto", lang: str = "en",
                  engine_manager: Optional[TTSEngineManager] = None) -> bool:
    """使用指定的TTS引擎合成文本。"""
    # 如果没有提供引擎管理器，创建一个新的
    if engine_manager is None:
        engine_manager = TTSEngineManager()
    
    # 执行合成
    return engine_manager.synthesize_text(text, output_path, engine_name=tts_engine, 
                                    tts_source=tts_source, lang=lang)





def build_output_dir(base_dir: Path, word: str) -> Path:
    """根据规则构建输出目录：file/首字母/第二个字母/完整单词"""
    normalized = word.strip().lower()
    first = normalized[0] if len(normalized) >= 1 else "_"
    second = normalized[1] if len(normalized) >= 2 else "_"
    out_dir = base_dir / first / second / normalized
    out_dir.mkdir(parents=True, exist_ok=True)
    return out_dir


def process_word(word: str, base_dir: Optional[Path] = None, tts_engine: str = "auto",
                 tts_source: str = "auto", show_progress: bool = False,
                 engine_manager: Optional[TTSEngineManager] = None) -> Path:
    # 如果没有提供引擎管理器，创建一个新的
    if engine_manager is None:
        engine_manager = TTSEngineManager()
    
    syllables = split_into_syllables(word)
    # 构建输出目录
    if base_dir:
        out_dir = base_dir / word
        out_dir.mkdir(parents=True, exist_ok=True)
    else:
        out_dir = build_output_dir(base_dir, word)

    # 逐音节生成对应 mp3 文件：syl_1.mp3, syl_2.mp3, ...
    total_syllables = len(syllables)
    for idx, syllable in enumerate(syllables, start=1):
        # 确定语言
        lang = 'zh' if any('\u4e00' <= char <= '\u9fff' for char in syllable) else 'en'
        print(f"  处理音节: {syllable} (语言: {lang})")
        
        mp3_path = out_dir / f"syl_{idx}.mp3"
        # 使用新的模块化合成系统
        synthesize_tts(syllable, mp3_path, tts_engine=tts_engine,
                      tts_source=tts_source, lang=lang,
                      engine_manager=engine_manager)
        
        # 显示进度
        if show_progress:
            print_progress(idx, total_syllables, f"单词 '{word}' 音节处理")
    
    if show_progress and total_syllables > 0:
        print()  # 换行
    
    # 同时保存一个 syllables.txt 方便查看
    (out_dir / "syllables.txt").write_text("|".join(syllables), encoding="utf-8")

    return out_dir


def load_config(config_path: Path) -> Dict[str, any]:
    """加载配置文件。"""
    if config_path.exists():
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                config = json.load(f)
            print(f"✓ 成功加载配置文件: {config_path}")
            return config
        except Exception as e:
            print(f"⚠ 加载配置文件失败: {e}")
    else:
        print(f"ℹ 配置文件不存在: {config_path}，使用默认配置")
    return {}

def save_default_config(config_path: Path) -> None:
    """保存默认配置文件。"""
    import platform
    # 根据操作系统选择默认引擎
    default_engine = "macos-say" if platform.system() == "Darwin" else "pyttsx3"
    
    default_config = {
        "tts_engine": default_engine,  # 根据操作系统选择默认引擎
        "tts_source": "local",  # 默认使用本地来源
        "baidu": {
            "app_id": "your_app_id",
            "api_key": "your_api_key",
            "secret_key": "your_secret_key"
        },
        "xunfei": {
            "app_id": "your_app_id",
            "api_key": "your_api_key",
            "secret_key": "your_secret_key"
        },
        "pyttsx3": {
            "rate": 150,
            "volume": 0.9
        }
    }
    
    # 确保目录存在
    config_path.parent.mkdir(parents=True, exist_ok=True)
    
    try:
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(default_config, f, indent=2, ensure_ascii=False)
        print(f"✓ 已创建默认配置文件: {config_path}")
        print("  请根据需要修改配置文件中的API密钥等信息")
    except Exception as e:
        print(f"⚠ 创建配置文件失败: {e}")

def parse_arguments() -> argparse.Namespace:
    """解析命令行参数。"""
    parser = argparse.ArgumentParser(
        description="英文单词音节拆分与语音合成工具"
    )
    
    parser.add_argument(
        "words", 
        nargs='*',
        help="要处理的英文单词"
    )
    
    parser.add_argument(
        "--tts-engine",
        choices=["auto", "pyttsx3", "macos-say", "gTTS", "baidu", "xunfei"],
        default="auto",
        help="选择TTS引擎: auto(自动选择), pyttsx3(本地), macos-say(macOS内置), gTTS(国外在线), baidu(百度AI), xunfei(讯飞)"
    )
    
    parser.add_argument(
        "--tts-source",
        choices=["auto", "local", "online"],
        default="auto",
        help="选择TTS来源: auto(自动选择), local(仅本地), online(仅在线)"
    )
    
    parser.add_argument(
        "--show-progress",
        action="store_true",
        help="显示处理进度"
    )
    
    parser.add_argument(
        "--config",
        type=Path,
        default=Path(__file__).parent / "config.json",
        help="配置文件路径 (默认: config.json)"
    )
    
    parser.add_argument(
        "--create-config",
        action="store_true",
        help="创建默认配置文件"
    )
    
    # 百度AI配置（可选）
    parser.add_argument(
        "--baidu-app-id",
        help="百度AI应用ID"
    )
    parser.add_argument(
        "--baidu-api-key",
        help="百度AI API Key"
    )
    parser.add_argument(
        "--baidu-secret-key",
        help="百度AI Secret Key"
    )
    
    # 讯飞配置（可选）
    parser.add_argument(
        "--xunfei-app-id",
        help="讯飞应用ID"
    )
    parser.add_argument(
        "--xunfei-api-key",
        help="讯飞API Key"
    )
    parser.add_argument(
        "--xunfei-secret-key",
        help="讯飞Secret Key"
    )
    
    return parser.parse_args()


def main(argv: List[str]) -> int:
    # 解析命令行参数
    args = parse_arguments()
    
    # 如果请求创建配置文件
    if args.create_config:
        save_default_config(args.config)
        return 0
    
    # 加载配置文件
    config = load_config(args.config)
    
    # 使用引擎管理器从配置和命令行参数创建引擎实例
    engine_manager = TTSEngineManager.create_from_config(config, args)
    
    # 确定使用的TTS引擎和来源
    tts_engine = args.tts_engine
    if tts_engine == "auto" and "tts_engine" in config:
        tts_engine = config["tts_engine"]
    
    tts_source = args.tts_source
    if tts_source == "auto" and "tts_source" in config:
        tts_source = config["tts_source"]
    
    # 设置默认值
    if tts_engine == "auto":
        tts_engine = "pyttsx3"
    if tts_source == "auto":
        tts_source = "local"
    
    # 如果没有提供单词，显示帮助信息
    if not args.words:
        print("错误: 请提供要处理的英文单词")
        print("使用示例:")
        print("  python main.py apple banana")
        print("  python main.py --create-config  # 创建配置文件")
        return 1
    
    print(f"使用TTS引擎: {tts_engine}")
    print(f"使用TTS来源: {tts_source}")
    
    project_root = Path(__file__).resolve().parent
    file_root = project_root / "file"
    file_root.mkdir(exist_ok=True)

    words = args.words
    total_words = len(words)
    
    for idx, word in enumerate(words):
        if not word.isalpha():
            print(f"跳过非纯字母单词: {word}")
            continue
            
        if args.show_progress:
            print(f"\n处理单词 {idx+1}/{total_words}: {word}")
        
        out_dir = process_word(
            word,
            base_dir=file_root,
            tts_engine=tts_engine,
            tts_source=tts_source,
            show_progress=args.show_progress,
            engine_manager=engine_manager
        )
        
        print(f"已生成: {word} -> {out_dir}")

    return 0


if __name__ == "__main__":
    # 注意：使用argparse时，不需要传递整个sys.argv
    # argparse会自动处理sys.argv[1:]
    sys.exit(main(sys.argv))
